/******************************************************************
 * Copyright @ 2023 广州牛师帮科技文化有限公司. All rights reserverd.
 * @file   src\hooks\Classifier.ts
 * @author 朱剑豪
 * @date   2023/05/11 17:42
 * @desc   分类器 根据条件返回值
 * 
 ******************************************************************/
import { useCallback, useMemo, useState } from "react";

export namespace Classifier {
  export interface IRule<K = any> {
    kind: K;
    predicate: () => boolean;
  }
  export interface IUseInits<K = any> {
    rules: IRule<K>[];
    fallback?: K;
  }
  export interface IUseInits2<K = any> {
    rules: IRule<K>[];
    fallback: K;
  }

  export function use<K>(inits: IUseInits2<K>): [K, () => void];
  export function use<K>(inits: IUseInits<K>): [K | undefined, () => void];
  export function use<K>(inits: IUseInits<K>): [K | undefined, () => void] {
    const { rules, fallback } = inits;
    const judge = useCallback(() => {
      return rules.find(v => v.predicate())?.kind || fallback;
    }, [rules, fallback]);

    const _kind = useMemo(() => judge(), []);
    const [kind, setKind] = useState<K | undefined>(_kind);
    const fire = useCallback(() => setKind(judge()), [judge]);
    return [kind, fire];
  }
}
